import axios from 'axios'
import Promise from 'bluebird'
// import token from '@/util/token'
import Cookies from 'js-cookie'
import $i18n from "@/pages/h5/i18n/index.js";


const service = axios.create({
  timeout: 60000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {

  var localStorageLang = null, hasCookie = false;

  try{
      localStorageLang = Cookie.get("django_language");
      if(localStorageLang){
        hasCookie = true;
      }
      if(localStorageLang && /^zh|zh-|zh_/i.test(localStorageLang)){
          localStorageLang = 'zh';
      }
  }catch(e){}

  if(hasCookie){
    $i18n.locale = localStorageLang;
  }

  config.headers['django-language'] = localStorageLang || $i18n.locale; //语言
  config.headers['Accept-Language'] = localStorageLang || $i18n.locale; //语言

  return config

}, error => {
  return Promise.reject(error)
})


const handleResponse = (res) => {
    if (res.data.success) {
        // 成功只返回data数据
        // return Promise.resolve(res.data.data)
        return Promise.resolve(res)
    } else {
        // status不为0为失败或错误情况
        return Promise.reject(res.data)
    }
}
const authority = (res) => {
    // 根据err_code 判断 是否有权限访问该页面的接口
    let body = res.body;
    if (body && $.isNumeric(body.error_code)) {
        body.error_code === 1 && (window['vueObj'] && window['vueObj'].$router.replace({ name: 'no_right' }))
    }
    let data = res.data;
    if (data && $.isNumeric(data.error_code)) {
        data.error_code === 1 && (window['vueObj'] && window['vueObj'].$router.replace({ name: 'no_right' }))
    }
}
export default {
    get(url, params) {
        let termStr = localStorage.getItem('currentTerm')
        let termObj = termStr ? JSON.parse(termStr) : null

        let apiHeader = localStorage.getItem('API_HEADER');
        let apiHeaderObj = apiHeader ? JSON.parse(apiHeader) : null;

        let _headers = localStorage.getItem('RequestHeaders') ? JSON.parse(localStorage.getItem('RequestHeaders')) : {};
        _headers['university-id'] = Cookies.get('university_id');
        _headers['platform-id'] = Cookies.get('platform_id') || 0;
        _headers['X-CSRFToken'] = Cookies.get('csrftoken');
        
        if(Cookies.get("dep") && url.indexOf("dep") == -1){
            var _dep = Cookies.get("dep");
            if(_dep) url = url.indexOf("?") != -1 ? url + "&dep=" + _dep : url + "?dep=" + _dep;
        }

        params = params || {};
        var _xtbz = "xtbz" in params &&  params["xtbz"] || "";
        if(_xtbz) _headers["xtbz"] = _xtbz;//业务线标识
        params['term'] = params['term'] ? params['term'] : termObj && termObj.value ? termObj.value : 'latest'
        params['uv_id'] = params['uv_id'] ? params['uv_id'] : apiHeaderObj && apiHeaderObj.school_id ? apiHeaderObj.school_id : (Cookies.get("university_id") ? Cookies.get("university_id") : '');

        let queryString = []
        Object.keys(params).forEach(key => params[key] !== undefined && queryString.push((`${key}=${params[key]}`)))
        if (queryString.length > 0) {
            queryString = queryString.join('&')
            if (url.indexOf('?') > -1) {
                url += `&${queryString}`
            } else {
                url += `?${queryString}`
            }
        }
        if (params['no_loading']) {
            $('#global_loading').hide()
        } else {
            $('#global_loading').show()
        }
        // return axios
        //   .get(url)
        //   .then(function (response, data) {
        //     $('#global_loading').hide()
        //     authority(response)
        //     return response
        //   })
        //   .then(handleResponse)
        //   .catch(error => {
        //     // 日志收集
        //     return Promise.reject(error)
        //   })
        return new Promise(function(resolve, reject) {
            service
                .get(url, {
                    headers: _headers
                })
                .then(function(response, data) {
                    $('#global_loading').hide()
                    authority(response)
                    resolve(response)
                })
                .then(handleResponse)
                .catch(error => {
                    reject(error)
                })
        });
    },

    post(url, params) {
        let termStr = localStorage.getItem('currentTerm');
        let termObj = termStr ? JSON.parse(termStr) : null;
        let term = termObj ? termObj.value : 'latest';

        let apiHeader = localStorage.getItem('API_HEADER');
        let apiHeaderObj = apiHeader ? JSON.parse(apiHeader) : null;

        let _headers = localStorage.getItem('RequestHeaders') ? JSON.parse(localStorage.getItem('RequestHeaders')) : {};
        _headers['university-id'] = Cookies.get('university_id');
        _headers['platform-id'] = Cookies.get('platform_id') || 0;
        _headers['X-CSRFToken'] = Cookies.get('csrftoken');

        if(Cookies.get("dep") && url.indexOf("dep") == -1){
            var _dep = Cookies.get("dep");
            if(_dep) url = url.indexOf("?") != -1 ? url + "&dep=" + _dep : url + "?dep=" + _dep;
        }

        params = params || {};
        let termParamsStr = `term=${params['term'] || term}`
        let uv_idParasStr = `uv_id=${apiHeaderObj && apiHeaderObj.school_id? apiHeaderObj.school_id: (Cookies.get("university_id")?Cookies.get("university_id"):'')}`
        if (url.indexOf('?') > -1) {
            url = `${url}&${termParamsStr}`
        } else {
            url += `?${termParamsStr}`
        }
        if (url.indexOf('uv_id') < 0) {
            url = `${url}&${uv_idParasStr}`
        }
        if (params['no_loading']) {
            $('#global_loading').hide()
        } else {
            $('#global_loading').show()
        }
        return service
            .post(url, params, {
                headers: _headers
            })
            .then(function(response, data) {
                $('#global_loading').hide()
                return response
            })
            .then(handleResponse)
            .catch(error => {
                return Promise.reject(error)
            })
    }
}
